using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;

namespace KaseyaWStestClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            btnSend.Enabled = false;
            XMLPATH = GetTestXmlPath();
        }

        private string XMLPATH = "";

        #region Core

        //form level copy of our client class
        Kaseya.KaseyaWSClient KasClient;

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                txtSessionID.Text = "";

                //initialize client with the URL to point to
                KasClient = new Kaseya.KaseyaWSClient(txtURI.Text);

                //login
                string SessionID = KasClient.Authenticate(txtUserName.Text, txtPassword.Text);

                //if we logged in, we can send transactions
                if (SessionID != "0")
                    btnSend.Enabled = true;

                //show the user the sessionID
                txtSessionID.Text = SessionID;

                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                //clear results display
                txtResponse.Clear();

                //send in the user's xml and display the result
                txtResponse.Text= KasClient.ProcessRequest(txtSend.Text);
                //display the modified xml as sent
                txtSend.Text = KasClient.SetSessionID(txtSend.Text);

                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region Convenience 

        private void btnViewSend_Click(object sender, System.EventArgs e)
        {

            OverWriteFile(@"C:\KaseyaWS\WStx.xml", XMLRemoveHeaders(txtSend.Text.ToString()));
            Process.Start("IExplore", @"C:\KaseyaWS\WStx.xml");

        }

        private void btnViewReceive_Click(object sender, System.EventArgs e)
        {

            OverWriteFile(@"C:\KaseyaWS\WSrx.xml", XMLRemoveHeaders(txtResponse.Text.ToString()));
            Process.Start("IExplore", @"C:\KaseyaWS\WSrx.xml");

        }

        private void btnClearSend_Click(object sender, System.EventArgs e)
        {
            txtSend.Text = "";                                            // txtSend.Clear();

        }

        private void btnClearReceive_Click(object sender, System.EventArgs e)
        {
            txtResponse.Text = "";                                         // txtResponse.Clear();

        }

        /// <summary></summary>
        /// <remarks>23Jan07 MNB: Added file name caption & clearing output.</remarks>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowse_Click(object sender, System.EventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.InitialDirectory = XMLPATH;
            
            fdlg.Title = "Browse";
            fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            string temp = "";
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                temp = fdlg.FileName;
                string temppath = Path.GetFullPath(temp).Replace(Path.GetFileName(temp), "");
                if (XMLPATH.ToUpper() != temppath.ToUpper())
                {
                    XMLPATH = temppath;
                    SaveTestXmlPath(XMLPATH);

                }

                txtSend.Text = ReadFile(temp);

                this.txtResponse.Clear();
                Application.DoEvents();
            }
        }

        

        private void btnCopyReceive_Click(object sender, System.EventArgs e)
        {
            DataObject m_data = new DataObject();
            m_data.SetData(DataFormats.Text, true, txtResponse.Text);
            Clipboard.SetDataObject(m_data, true);
        }

        private void btnCopySend_Click(object sender, System.EventArgs e)
        {
            DataObject m_data = new DataObject();
            m_data.SetData(DataFormats.Text, true, txtSend.Text);
            Clipboard.SetDataObject(m_data, true);
        }


        

        #endregion

        #region Helpers

        private string XMLRemoveHeaders(string xml)
        {
            string xsdDefaultRef = @"xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""";
            string xsdDefaultRef1 = @"xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""";
            string xmlHeader8 = @"<?xml version=""1.0"" encoding=""utf-8""?>";
            string xmlHeader16 = @"<?xml version=""1.0"" encoding=""utf-16""?>";
            string xmlHeaderDAL = @"<?xml version=""1.0""?>";
            string s = xml;
            s = s.Replace(xsdDefaultRef, "");
            s = s.Replace(xsdDefaultRef1, "");
            s = s.Replace(xmlHeader8, "");
            s = s.Replace(xmlHeader16, "");
            s = s.Replace(xmlHeaderDAL, "");
            return s;

        }

        private string ReadFile(string strFileName)
        {
            FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string s = sr.ReadToEnd();
            sr.Close();
            fs.Close();
            return s;
        }


        private void OverWriteFile(string strFileName, string strOutput)
        {
            FileStream fs = new FileStream(strFileName, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(strOutput);
            sw.Close();
            fs.Close();
        }

        private string GetTestXmlPath()
        {
            try
            {
                return ReadRegistryValueInLocalMachine(@"SOFTWARE\Kaseya\", "TestXmlPath", DefaultXmlPath());
            }
            catch
            {
                return "";
            }
        }

        private void SaveTestXmlPath(string Path)
        {
            try
            {
                WriteRegistryValueInLocalMachine(@"SOFTWARE\Kaseya\", "TestXmlPath", Path);
            }
            catch
            {

            }
        }

        private string DefaultXmlPath()
        {
            string temp = ReadRegistryValueInLocalMachine(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\KServer.exe\", "Path", @"c:\kaseya\KServer");
            temp = temp.ToUpper().Replace("KServer".ToUpper(), "vsaWS");
            return temp + @"\TestXML\";
        }
                

        private string ReadRegistryValueInLocalMachine(string KeyPath, string EntryName, string DefaultValue)
        {

            string temp = ReadRegistryValueInLocalMachine(KeyPath, EntryName);

            if (string.IsNullOrEmpty(temp))
            {
                WriteRegistryValueInLocalMachine(KeyPath, EntryName, DefaultValue);
                return DefaultValue;
            }
            else
            {
                return temp;
            }
        }

        private string ReadRegistryValueInLocalMachine(string KeyPath, string EntryName)
        {
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey sk;
            try
            {
                sk = rk.OpenSubKey(KeyPath);
            }
            catch
            {
                throw new Exception("Invalid Registry Key Path  " + KeyPath);
            }

            if (sk == null)
            {
                throw new Exception("Invalid Registry Key Path  " + KeyPath);
            }

            try
            {
                return sk.GetValue(EntryName).ToString();
            }
            catch
            {
                return "";
            }

        }

        private void WriteRegistryValueInLocalMachine(string KeyPath, string EntryName, string EntryValue)
        {
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey sk;

            try
            {
                sk = rk.CreateSubKey(KeyPath);

            }
            catch
            {
                throw new Exception("Invalid Registry Key Path  " + KeyPath);
            }

            if (sk == null)
            {
                throw new Exception("Invalid Registry Key Path  " + KeyPath);
            }

            sk.SetValue(EntryName, EntryValue);

        }

        #endregion

    }
}